package com.example.es.myt;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

public class ESTest_Client_Insert {
    public static void main(String[] args) throws IOException {
        //创建客户端
        RestHighLevelClient restHighLevelClient=new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost",9200,"http"))
        );

        IndexRequest request=new IndexRequest();
        request.index("user").id("1001");
        User user=new User();
        user.setAge(30);
        user.setSex("男");
        user.setName("twd");
        //插入数据
        ObjectMapper objectMapper=new ObjectMapper() ;
        String userJson=objectMapper.writeValueAsString(user);
        request.source(userJson, XContentType.JSON);

        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println("索引操作"+response.getResult());

        //关闭
        restHighLevelClient.close();
    }
}
